define(function (require, exports, module) {
    var template = require("template");
    var Ajax = require("ajax");
    var layer = require("layer");
    var pagination = require('pagination');
    var util = require('util');
    
    var screenObj = function (callback) {
        this.init.apply(this,arguments);
    };
    screenObj.prototype = {
        constructor: screenObj,
        options: {},
        init: function (options) {
            var t = this;
            t.options = $.extend({},t.options,options);
            $(".tipConNav").text("中周搜索列表");
            $(window).off('scroll');
            $("#rightConBox").html(template("monitorScreenTemp",{}));
            t.initData();
            t.mask();
            t.queryInformation();
            t.loadInitList(1);
            t.isCollectionEvent();
            t.loadWeixinEvent();
            var listNum = '';
        },
        initData: function(){
        	var articleTypesText = $.cookie("articleTypesText");
        	var contentsText = $.cookie("contentsText");
        	var wayspanText = $.cookie("wayspanText");
            $("#articleType").val(articleTypesText);
            $("#search_input").val(contentsText);
            if(wayspanText=="authors"){
            	$('.waySelect .iconfont[data-key="authors"]').removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
            }else{
            	$('.waySelect .iconfont[data-key="contents"]').removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
            }
            
            var len = $("#ul_select li").length;
            for(var i=0;i<len; i++){
            	var types = $("#ul_select li a").eq(i).attr("data-key");
            	if(articleTypesText==types){
            		$("#ul_select li a").removeClass('cur');
            		$("#ul_select li a").eq(i).addClass('cur');
            	}
            }
			$("#ul_select li a").on('click',function(){
                var $type = $(this);
                if(!$type.hasClass("cur")){
                    $("#ul_select li a").removeClass("cur");
                }
                $type.addClass("cur");
                $("#articleType").val($(".cur").attr("data-key"));
            });	
            
            $("#ui_select li a").removeClass("cur");
        },
        
        mask: function(){
            $(".mask").css("height",$(document).height());
            $(".mask").css("width",$(document).width());
        },
        
        loadInitList: function(pageIndex) {
			var t = this, jsonObj={};
			var articleType = $("#articleType").val();
			if($('.waySelect .checked').attr('data-key')=='authors'){
				jsonObj = {
					pageIndex: pageIndex,
					articleType: articleType||null,
					author: $("#search_input").val()?$("#search_input").val().trim():null	
				}
			}else{
				jsonObj = {
					pageIndex: pageIndex,
					articleType: articleType||null,
					title: $("#search_input").val()?$("#search_input").val().trim():null	
				}
			}
			Ajax.ajax({
				url: localhost + "Monitoring/findzhongzhouSeek.do",
//				url: localhost + "json/findzhongzhouSeek.json",
				data: jsonObj,
				beforeSend: function() {
					if(pageIndex==1){
						$('#screen_table>tbody').html(template("loadingDom"));
					}else{
						$("#listDom").html('');
						$("#listDom").append("<div class='loadingMoreBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
					}
				},
				success: function(data) {
					if(data.returnCode == 10000){
						if(data.returnData && data.returnData.length > 0) {
							$(".loadingBox").remove();
							$(".loadingMoreBox").remove();
							var tHead = '',tList= '',sourceName='',isCollection='',colors='',colors_nature='',
								dataList = data.returnData;
							var	searchNums = dataList[0].count;
							tHead = "<tr class='th'><th></th><th>序号</th><th>标题</th><th>来源</th><th>作者</th><th>时间</th><th>性质</th><th>收藏</th></tr>";
			                for (var i = 0; i < dataList.length; i++) {
			                	var item = dataList[i]; 
			                    if(item.articleType=="News"){
			                    	sourceName = item.websiteName;
			                    }else if(item.articleType=="Micro"){
			                    	sourceName = "微博";
			                    }else if(item.articleType=="BBS"){
			                    	sourceName = "论坛";
			                    }else if(item.articleType=="WeiXin"){
			                    	sourceName = "微信";
			                    }
			                    if(item.nature=='负面'){
			                    	colors_nature = "red";
			                    }else{
			                    	colors_nature = "green";
			                    }
			                    if(pageIndex==1){
			                    	if(i==0){
			                    		listNum =1;
			                    	}else{
			                    		listNum++;
			                    	}
			                    	
			                    }else{
			                    	listNum++;
			                    }
			                    tList += '<tr><td><i class="iconfont icon-fangxingweixuanzhong" data-id="'+item.id+'"></i></td>';
			                    tList += '<td>'+listNum+'</td>';
			                    
			                    //表格
			                    if(item.articleType=="WeiXin"){
			                    	if(localStorage.getItem(item.articleId)!=null){
			                    		tList += '<td><a class="changeColor" data-type="weixin" data-ifmId="'+ item.ifmId +'" data-articleId="'+ item.articleId +'" href="javascript:;">'+item.title+'</a></td>';
			                    	}else{
			                    		tList += '<td><a data-type="weixin" data-ifmId="'+ item.ifmId +'" data-articleId="'+ item.articleId +'" href="javascript:;">'+item.title+'</a></td>';
			                    	}
			                    }else{
			                    	tList += '<td><a target="_blank" href="' + item.url + '">'+item.title+'</a></td>';
			                    }
			                    
			                    tList += "<td>"+ sourceName +
			                    		 "</td><td>"+ item.author +
			                    		 "</td><td>"+ item.releaseTime +
			                    		 "</td><td class="+ colors_nature +">"+ item.nature + "<td><a href='javascript:;' ";
			                    
			                    if(item.isCollection==0){
			                    	isCollection = "收藏";
			                    	colors = "black";
			                    }else{
			                    	isCollection = "已收藏";
			                    	colors = "grey";
			                    }
			                    
			                    tList += '<td><a href="javascript:;" ';
			                    tList += isNull(item.isCollection,'data-isCollection=');
								tList += isNull(item.nature,'data-nature=');
								tList += isNull(item.ifmId,'data-ifmid=');
								tList += isNull(item.articleId,'data-articleid=');
								tList += isNull(sourceName,'data-articleType=');
								tList += isNull(item.author,'data-enshrineAuthor=');
								tList += isNull(item.title,'data-enshrineTitle=');
								tList += isNull(item.url,'data-enshrineUrl=');
								tList += isNull(item.releaseTime,'data-releaseTime1=');
								tList += isNull(item.nature,'data-nature=');
								tList += isNull(item.reprintNumb,'data-reprintNum=');
								
			                    tList += ' class="collect '+ colors +'">'+isCollection+'</a></td>';
			                    tList += '</tr>';
			                }
			                
							//如果属性值为空，那么此元素就不添加该属性
							function isNull(isText,data){
								if(isText||isText=='0'){
									var tL = data + "'"+isText+"'";
								}else{
									tL = '';
								}
								return tL;
							}
			               
							if(articleType==$("#articleType").val()){
								$("#searchNums").text("共搜索出 "+searchNums+" 条数据");
				                if(pageIndex==1){
				                	$('#screen_table>tbody').html('');
				                	$('#screen_table>tbody').append(tHead+tList);
				                }else{
				                	if(pageIndex!=$("#pageIndexScreen").val()){ //防止下拉滚动后重复加载数据
	    			            		$("#pageIndexScreen").val(pageIndex);
	    			            		$('#screen_table>tbody').append(tList);
				                	}
				                }								
							}else{
								return;
							}
			                util.CutOff();      //截断过长文字
			                t.loadPage(pageIndex);
			                if(!(pageIndex==1 && item.length<15)){
			                	if($(".morePage").length<1){ 
			                		$("#listDom").append("<div class='morePage animated fadeIn'><span>下拉加载更多</span></div>");
			                	}
			                }
						} else {
							$(".loadingBox").remove();
							$(".loadingMoreBox").remove();
							$(window).off('scroll');
							if(pageIndex==1){
								$('#screen_table>tbody').html(template("noDataDom"));
								$("#searchNums").text("共搜索出 0 条数据");
							}else{
								if($(".lastPage").length<1){ 
									$("#listDom").append("<div class='lastPage animated fadeIn'><span>没有更多内容</span></div>");
								}
							}	
						}
					}	
				}
			});
		},
		loadPage: function(pageIndex) {
			var t = this;
			//获取页面顶部被卷起来的高度
			function scrollTop() {
				return Math.max(
					//chrome
					document.body.scrollTop,
					//firefox/IE
					document.documentElement.scrollTop);
			}
			//获取页面文档的总高度
			function documentHeight() {
				//现代浏览器（IE9+和其他浏览器）和IE8的document.body.scrollHeight和document.documentElement.scrollHeight都可以
				return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
			}
			function windowHeight() {
				return(document.compatMode == "CSS1Compat") ?
					document.documentElement.clientHeight :
					document.body.clientHeight;
			}
			if(window.location.href.indexOf("admin/monitor_screen")>-1){
			}else{
				return false;
			}
			var isloading = false;
			$(window).on('scroll', function() {
				//判定是否加载中，防止重复加载
				if(!isloading){
					//滚动条卷起来的高度 + 窗口高度 >= 文档的总高度 - 50/*这里将滚动响应区域高度取50px*/；如果这个判断为true则表示滚动条滚动到了底部。
					if(scrollTop() + windowHeight() >= (documentHeight() - 50)) {
						isloading = false;
						pageIndex = parseInt(pageIndex)+ 1;
						if(window.location.href.indexOf("admin/monitor_screen")>-1){
						}else{
							return false;
						}
						t.loadInitList(pageIndex);
						isloading = true;
					}
				}
			});
		},
		
        //方案查询
        queryInformation: function(){
            var t = this;
			$("#ul_select li a").on('click',function(){
                var $type = $(this);
                if(!$type.hasClass("cur")){
                    $("#ul_select li a").removeClass("cur");
                }
                $type.addClass("cur");
                $("#articleType").val($(".cur").attr("data-key"));
                
			});
            
        	$(".searchBtn, #ul_select li a").on('click',function(){
        		//防止重复滚动加载数据
        		$(window).off('scroll');
        		t.loadInitList(1);
        	});
            //键盘“enter”搜索
            $("#search_input").keydown(function(event) {
                if (event.keyCode == "13") {//keyCode=13是回车键
            		//防止重复滚动加载数据
            		$(window).off('scroll');
            		t.loadInitList(1);
                }
            });
            //查询方式的单选
			$('.waySelect .iconfont').on('click',function(){
            	if(!$(this).hasClass('checked')){
            		$(this).removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
            		$(this).parent().siblings().children('i').removeClass('checked').removeClass('icon-check').addClass('icon-fangxingweixuanzhong');
            	}
            });
			
			var selectNums = [];
			//单个选中
			$('#screen_table>tbody').undelegate().delegate('.iconfont','click',function(){
            	if($(this).hasClass('checked')){
            		$(this).removeClass('checked').removeClass('icon-check').addClass('icon-fangxingweixuanzhong');
            		for(var i=0;i<selectNums.length;i++){
            			if($(this).attr('data-id')==selectNums[i]){
            				selectNums.splice(i, 1);
            				break;
            			}
            		}
            	}else{
            		$(this).removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
            		selectNums.push($(this).attr('data-id'));
            	}
            });
			
            //全选
			$('.allBtn').on('click',function(){
				selectNums.length = 0;
				var len = $("#screen_table .iconfont").length;
				if($(this).attr("data-all")==0) {
					$(this).attr("data-all",1);
//					$("#screen_table .iconfont").removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
					$('#screen_table .iconfont').each(function(){
	                    $(this).removeClass('icon-fangxingweixuanzhong').addClass('icon-check').addClass('checked');
	                    selectNums.push($(this).attr('data-id'));
	                });
				} else {
					$(this).attr("data-all",0);
					$("#screen_table .iconfont").removeClass('checked').removeClass('icon-check').addClass('icon-fangxingweixuanzhong');
					selectNums.length = 0;
				}

            });
			
            //批量导出
            $('.downExcelBtn').click(function(){
                if(selectNums.length > 0 && selectNums.length <= 500) {
            		var paramsObj = {
        				"id":selectNums.join()
        			}
        			//利用post表单的方式进行导出操作
        			function openPostWindow(postUrl, paramsObj, name) {      
        	            var postForm = document.createElement("form");      
        	            postForm.id="postForm";      
        	            postForm.method="post";      
        	            postForm.action=postUrl;      
        	            postForm.target=name;      
        	             
        	            function getParams(objName,objValue){
        	                var objInput = document.createElement("input");      
        	                objInput.type="hidden";      
        	                objInput.name= objName;  
        	                objInput.value= objValue;    
        	                postForm.appendChild(objInput);   
        	            }
        	            getParams("Id",paramsObj.id);
        	            document.body.appendChild(postForm);
        	            postForm.submit();
        	            document.body.removeChild(postForm);	                  
        			} 
        			var url = localhost + 'Monitoring/ExportExecl.do';
        			openPostWindow(url,paramsObj,name);
                	
                } else if(selectNums.length > 500){
                    layer.msg('单次导出信息仅限于500条',{time: 2000});
                } else {
                    layer.msg('请选择导出的内容',{time: 2000});
                }
                
            });
        },
        
        //收藏
        isCollectionEvent: function(){
        	$('.monitor_table > tbody').delegate('.collect','click',function(){
        		$(this).removeClass('collect');
        		var t = $(this);
        		if($(this).attr("data-iscollection")==1){
        			return false;
        		}
        		var articleId = $(this).attr("data-articleid");
        		var ifmId = $(this).attr("data-ifmid");
        		var articleType = $(this).attr("data-articleType");
        		var enshrineAuthor = $(this).attr("data-enshrineAuthor");
        		var enshrineTitle = $(this).attr("data-enshrineTitle");
        		var enshrineUrl = $(this).attr("data-enshrineUrl");
        		var releaseTime1 = $(this).attr("data-releaseTime1");
        		var params = {
        			articleId: articleId,
        			articleType: articleType,
        			enshrineAuthor: enshrineAuthor,
        			enshrineTitle: enshrineTitle,
        			enshrineUrl: enshrineUrl,
        			releaseTime1: releaseTime1,
        			ifmId: ifmId,
        			reprInt:0
        		}
    			Ajax.ajax({
    				url: localhost + "enshrine/insert.do",
    				data: params,
    				success: function(data) {
    					if(data.returnCode == 10000){
    						layer.msg(data.returnMessage,{time: 2000},function(){
    							t.attr("data-iscollection",1).text("已收藏").css({"color":"#7B8FA6","text-decoration":"none"});
    						});
    					} 
    				}
    			});
        	});
        },
        //微信操作
        loadWeixinEvent:function(){
            var t =this;
            $('.monitor_table>tbody').delegate('a', 'click', function () {
                var type = $(this).attr('data-type');
                if(type =="weixin"){
                    if(!$(this).hasClass("changeColor")){
                    	$(this).addClass("changeColor");
                    }
                	
                	var articleId = $(this).attr('data-articleId');
                	var ifmId = $(this).attr('data-ifmId');
                	
                	var params ={
                		articleId:articleId,
                		ifmId:ifmId
                	}
                	Ajax.ajax({
        				url: localhost + "Monitoring/findSingle.do",
        				data: params,
        				success: function(data) {
        					if(data.returnCode == 10000){
        	                    var title = data.returnData.title;
        	                    var author = data.returnData.author;
        	                    var releaseTime = data.returnData.releaseTime;
        	                    var source = data.returnData.source;
        	                    var content = data.returnData.content;
        	                    var reg = /\n/g;
        	                    content = content.replace(reg, '<br>');
        	                    var index = layer.open({
        	                        title: '&nbsp;',
        	                        type: 1,
        	                        closeBtn: 1,
        	                        skin: 'inner_url',
        	                        content: "<div class='weixin_title'>" + title + "</div>" +"<div class='weixin_source'><span>"+ releaseTime+"</span><span>"+ author +"</span><span>"+ source+"</span></div><div class='weixin_content'>"+ content + "</div>",
        	                        area: ['80%', '650px'],
        	                        btn:['关闭'],
        	                        maxmin: false,
        	                        scrollbar: false, // 父页面 滚动条 禁止
        	                        shadeClose: true
        	                    });
        	                    localStorage.setItem(articleId, new Date().valueOf());
        					}
        				}
        			});
                }
            });
        }
		
    };
    module.exports = screenObj;
});

